<template>
  <div>
    <el-tree
      :data="data"
      node-key="id"
      :draggable="type == 'add' || type == 'edit'"
      ref="selectTree"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expand-all="true"
      :current-node-key="highlightedNodeId"
      @node-drop="handleDrop"
      @node-click="handleClick"
      :allow-drop="allowDrop"
    >
      <div v-if="exceptionType != 'abnormal'" class="custom_tree_node" slot-scope="{ data }">
        <div style="display: flex; align-items: center">
          <div class="state" v-if="data.type == 3 || data.type == 4">
            <div class="flex stateIcons">
              <div class="exam_icon" v-if=" data.examId && data.submitType == 1 && !data.leaderScorePercent">
                考
              </div>
              <div class="exam_icon" v-if="data.examId &&  (data.submitType == 2 || (data.submitType == 1 && data.leaderScorePercent > 0))">
                组
              </div>
              <div class="leader_icon" v-if="data.homeworkId && data.homeworkSubmitType == 1 && !data.homeworkLeaderScorePercent">
                作
              </div>
              <div class="leader_icon" v-if="data.homeworkId && (data.homeworkSubmitType == 2 || (data.homeworkSubmitType == 1 && data.homeworkLeaderScorePercent > 0))">
                组
              </div>
            </div>
          </div>

          <div
            v-if="!data.showRename"
            :style="{
                width: `calc(280px - 90px - ${(data.level - 1) * 16}px`,
              }"
            class="label"
          >
            <tooltip :text="data.name" position="top-start" width="100%">
            </tooltip>
          </div>
          <div
            @click.stop=""
            v-if="data.showRename"
            :style="{
                width: `calc(280px - 90px - ${(data.level - 1) * 16}px`,
              }"
            class="label"
          >
            <el-input
              clearable
              size="small"
              oninput="value=value.replace(/\//g, '')"
              ref="resetName"
              @blur="editName(data)"
              @change="editName(data, 2)"
              v-model="data.name"
              placeholder="请输入名称"
              style="width: 100%"
            />
          </div>
        </div>
        <!-- 教师端课程目录 -->
        <div class="flex_center">
          <div
            class="must_learn"
            v-if="
                data.mustLearnStatus == 1 && (data.type == 3 || data.type == 4)
              "
          >
            必学
          </div>
          <div
            class="choose_learn"
            v-if="
                data.mustLearnStatus == 2 && (data.type == 3 || data.type == 4)
              "
          >
            选学
          </div>
          <div v-if="type == 'add' || type == 'edit'" class="btn">
            <el-dropdown placement="bottom-start" trigger="click">
              <img
                class="more"
                src="@/assets/images/courseAdd/more.png"
                alt="加载失败"
                @click.stop=""
              />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="data.type != 3 && data.type != 4 && data.type != 5"
                  @click.native.stop="handleEmit(data, 'addLink')"
                >
                  <span>添加子目录</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="data.type == 5"
                  @click.native.stop="handleEmit(data, 'addFinish')"
                >
                  <span>添加终结性考核</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="data.type != 3 && data.type != 4 && data.type != 5"
                  @click.native.stop="handleEmit(data, 'addContent')"
                >
                  <span>添加内容层</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click.native.stop="handleEmit(data, 'rename')"
                >
                  <span>重命名</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="data.type != 5"
                  @click.native.stop="handleEmit(data, 'delete')"
                >
                  <span>删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div v-else class="custom_tree_error" slot-scope="{ data }">
        <div class="stateIcons_exception" v-if="data.type == 3 || data.type == 4">
          <div class="exam_icon" v-if="data.exceptionIndexVO.hasExamException">
            考
          </div>
          <div class="leader_icon" v-if="data.exceptionIndexVO.hasHomeworkException">
            作
          </div>
          <div class="practice_icon" v-if="data.exceptionIndexVO.hasPracticeException">
            练
          </div>
        </div>
        <div :style="{ width: `calc(280px - 90px - ${(data.level - 1) * 16}px` }" class="label">
          <tooltip :text="data.name" position="top-start" width="100%">
          </tooltip>
        </div>
      </div>
    </el-tree>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="showDelete = false"
      :visible="showDelete"
      width="500px"
      append-to-body
    >
      <div slot="title">删除确认</div>
      <div v-loading="showSecLoading">
        <div class="delete_content" v-if="!showSecDelete">
          <div>
            题库中目录与课程目录相同，删除本节点同时会删除题库中目录和目录下的题目。当前有其他考核使用了题库中本目录下的题目。
          </div>
          <div class="color_orange">选择删除:同时删除题库中试题。</div>
          <div class="color_orange">选择不删除：将题目中的题目归到上一层级。</div>
        </div>
        <div class="delete_content" v-if="showSecDelete">
          <div>
            题目在以下位置被使用，强制删除后可能导致试卷异常，是否仍确认删除？
          </div>
          <div class="datalist_tree">
            <el-tree
              :data="dataList"
              node-key="id"
              ref="selectTree"
              :expand-on-click-node="false"
              :highlight-current="true"
              :default-expand-all="true"
            >
              <div class="custom_tree_error" slot-scope="{ data }">
                <div class="stateIcons_exception" v-if="data.type == 3 || data.type == 4">
                  <div class="exam_icon" v-if="data.exceptionIndexVO.hasExamException">
                    考
                  </div>
                  <div class="leader_icon" v-if="data.exceptionIndexVO.hasHomeworkException">
                    作
                  </div>
                  <div class="practice_icon" v-if="data.exceptionIndexVO.hasPracticeException">
                    练
                  </div>
                </div>
                <div :style="{ width: `calc(280px - 90px - ${(data.level - 1) * 16}px`}" class="label">
                  <tooltip :text="data.name" position="top-start" width="100%">
                  </tooltip>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!showSecDelete" @click="showSecondDia"
        >删 除
        </el-button
        >
        <el-button v-if="!showSecDelete" type="primary" @click="notDelete"
        >不删除
        </el-button
        >
        <el-button v-if="showSecDelete" @click="showSecDelete = false"
        >取 消
        </el-button
        >
        <el-button v-if="showSecDelete" type="primary" @click="sureDelect"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getHasTopic,
  getIndexListWhichUsedTopicInThisIndex
} from '@/api/course/course'

export default {
  name: 'courseTrees',
  data() {
    return {
      oldName: '',
      // 新增
      highlightedNodeId: '',
      selectData: '',
      dataList: [],
      showDelete: false,
      showSecLoading: false,
      showSecDelete: false
    }
  },
  props: {
    selectId: {
      type: [String, Number],
      default: ''
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    type: {
      type: String,
      default: ''
    },
    exceptionType: {
      type: String,
      default: ''
    }
  },
  watch: {
    selectId(val) {
      if (val) {
        this.highlightedNodeId = val
        this.$refs.selectTree.setCurrentKey(this.highlightedNodeId)
      }
    },
    data(val, oldVal) {
      if (oldVal.length == 0) {
        if (val.length > 0) {
          this.$nextTick(() => {
            this.highlightedNodeId = val[0].id
            this.$refs.selectTree.setCurrentKey(this.highlightedNodeId)
            this.$emit('handleClick', val[0])
          })
        }
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    async showSecondDia() {
      // 新
      this.showSecLoading = true
      try {
        let res = await getIndexListWhichUsedTopicInThisIndex(
          this.selectData.id
        )
        const { code, data } = res
        if (code == 200) {
          this.dataList = data
          if (data.length > 0) {
            this.showSecDelete = true
          } else {
            this.showDelete = false
            this.selectData.deleteTopic = true
            this.$emit('delete', this.selectData)
          }
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.showSecLoading = false
      }
    },
    notDelete() {
      this.showDelete = false
      this.selectData.deleteTopic = false
      this.$emit('delete', this.selectData)
    },
    sureDelect() {
      this.showDelete = false
      this.selectData.deleteTopic = true
      this.$emit('delete', this.selectData)
    },
    // 很多地方在组件外调用，删除会报错，不清楚具体逻辑先加回来 20251105 杜
    hightFirst() {
      console.log('高亮')
      this.$nextTick(() => {
        this.highlightedNodeId = this.data[0].id
        this.$refs.selectTree.setCurrentKey(this.data[0].id)
        this.$emit('handleClick', this.data[0])
      })
    },
    handleClick(data) {
      this.$emit('handleClick', data)
    },
    //设置子目录可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      //注掉的是同级拖拽
      if (draggingNode.level === dropNode.level) {
        // 获取父节点信息
        const draggingParent = draggingNode.parent
        const dropParent = dropNode.parent
        if (draggingParent !== dropParent) {
          return false
        }
        return type === 'prev' || type === 'next'
      } else {
        // 不同级进行处理
        return false
      }
    },
    expandAll() {
      this.$nextTick(() => {
        this.expandAllNodes(this.$refs.selectTree.store.root)
      })
    },
    collapseAll() {
      this.$nextTick(() => {
        this.collapseAllNodes(this.$refs.selectTree.store.root)
      })
    },
    expandAllNodes(node) {
      if (node) {
        node.expanded = true
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.expandAllNodes(childNode)
          })
        }
      }
    },
    collapseAllNodes(node) {
      if (node) {
        node.expanded = false
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.collapseAllNodes(childNode)
          })
        }
      }
    },
    // 拖拽排序
    async handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', draggingNode, dropNode, dropType, ev)
      let parentChildren = this.findParentChildrenById(
        this.data,
        draggingNode.data.id,
        draggingNode.data.level
      )
      let ids = []
      if (parentChildren) {
        parentChildren.forEach((item) => {
          ids.push(item.id)
        })
        this.$emit('sort', ids.join(','))
      }
    },
    //返回节点所在层级的父节点的 children 数组
    findParentChildrenById(data, checkId, level, parentChildren = null) {
      if (level == 1) {
        let firstChildren = []
        for (let item of data) {
          firstChildren.push(item)
        }
        return firstChildren
      }
      for (let item of data) {
        if (item.id === checkId) {
          return parentChildren
        }
        if (item.children) {
          let result = this.findParentChildrenById(
            item.children,
            checkId,
            level,
            item.children
          )
          if (result) {
            return result
          }
        }
      }
      return null
    },
    async handleEmit(data, name) {
      if (name == 'rename') {
        this.oldName = ''
        this.oldName = data.name
        data.showRename = true
        this.$nextTick(() => {
          this.$refs['resetName'].focus()
        })
      } else {
        if (name == 'delete') {
          const loading = this.$loading({
            lock: true,
            text: '正在检查目录...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          try {
            let res = await getHasTopic(data.id)
            const { code } = res
            if (code == 200) {
              if (res.data) {
                this.showDelete = true
                this.selectData = data
              } else {
                data.deleteTopic = false
                this.$emit(name, data)
              }
            }
          } catch (e) {
            console.error(e)
          } finally {
            loading.close()
          }
        } else {
          this.$emit(name, data)
        }
      }
    },
    editName(data, type) {
      console.log('编辑名称 editName', data.name, type)
      if (type == 2) {
        // this.$emit("rename", data);
      } else {
        if (data.name.trim() == '') {
          data.name = this.oldName
          data.renameFail = true
          this.$modal.msgWarning('目录名称不能为空！')
        } else {
          data.renameFail = false
        }
        data.showRename = false
        this.$emit('rename', data)
      }
    }
  }
}
</script>

<style scoped lang="scss">

.custom_tree_node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px 0 0;
  box-sizing: border-box;

  .state {
    position: relative;
    justify-content: flex-end;

    .exam_icon {
      width: 16px;
      height: 16px;
      background: #fa6400;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }

    .leader_icon {
      width: 16px;
      height: 16px;
      background: #4e8dff;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }
  }

  .flex_center {
    display: flex;
    align-items: center;

    .must_learn {
      color: rgb(40, 178, 139);
      background: rgb(196, 236, 226);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .choose_learn {
      color: rgb(44, 172, 255);
      background: rgb(213, 238, 255);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btn {
      width: 20px;
      height: 20px;
      overflow: hidden;
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;

      .more {
        width: 18px;
        height: 12px;
      }
    }
  }

  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.custom_tree_error {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0 8px 0 0;
  box-sizing: border-box;

  .stateIcons_exception {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .exam_icon {
      width: 16px;
      height: 16px;
      background: #fa6400;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }

    .leader_icon {
      width: 16px;
      height: 16px;
      background: #4e8dff;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }

    .practice_icon {
      width: 16px;
      height: 16px;
      background: #fead22;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }
  }

  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.stateIcons {
  position: absolute;
  width: 40px;
  top: -8px;
  right: 0;
  justify-content: flex-end;
}


::v-deep .el-tree-node__content {
  height: 40px;
}

.title {
  width: 100%;
  display: flex;
  justify-content: center;
  font-weight: bold;
}

.delete_content {
  .datalist_tree {
    width: 100%;
    height: calc(100vh - 430px);
    overflow: auto;
  }
}

.color_orange {
  margin-top: 10px;
  color: #fa6400;
}
</style>
